#define _CRT_SECURE_NO_WARNINGS
#include<chrono>
#include "MemoryPool.h"
//展示内存池的应用

//粒子
struct Particle
{
	double x, y, z;
	double lifeTime;
	Particle(double a=0.0,double b= 0.0,double c= 0.0,double time= 0.0)
		:x(a),y(b),z(c),lifeTime(time)
	{
	}
	void* operator new(size_t size);
	void operator delete(void* ptr) noexcept;//noexcept保证不会抛出异常
		//如果delete抛出异常，会导致内存泄漏
	//简单的业务函数
	void update()
	{
		lifeTime--;
	}
};
// 定义内存池对象
static MyMemoryPool::FixedSizePool  g_Particle(sizeof(Particle), 4096);
void* Particle::operator new(size_t size)
{
	return g_Particle.allocate();
}
void Particle::operator delete(void* ptr) noexcept
//noexcept保证不会抛出异常
//如果delete抛出异常，会导致内存泄漏
{
	g_Particle.deallocate(ptr);
}

int main()
{
	vector<Particle*>vec;
	vec.reserve(10000);
	//创建物体对象
	for (size_t i = 0; i < 10000; ++i)
	{
		Particle* p = new Particle{0.0,0.0,0.0,0.0 };
		vec.push_back(p);
		
	}
	//其余的业务逻辑代码

	//销毁物体对象
	for (auto* p : vec) delete p;//这里调用的是内存池的delete不是系统自带的delete
	//测试
	cout << "block_Size=" << g_Particle.Get_block_Size() <<"   "
		<< "block_Per_Page=" << g_Particle.Get_block_Per_Page() << endl;
	return 0;
}
